<?php

class gameModel
{

    /**
     * 基类
     * @var object
     */
    private $base;

    /**
     * Mysql 连接
     * @var resources
     */
    private $db;

    /**
     * Redis 连接
     * @var resources
     */
    private $redis;
    private $_appId = 'wx6e9f935be224ef2e';
    private $_appSecret = 'fda90d889cf846234720ee5d414a336c';
    private $_uri = 'https://open.weixin.qq.com/connect/oauth2/';
    private $_redirectUrl = "http://irun.hupu.com/gameWeb/wxcallback";

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }
    
    public function bindUser($uid,$city){
        $row = [
            'uid' => $uid,
            'city' => $city,
            'addtime' => time(),
            'chapter' => 1
        ];
        $this->db->insertRowTable('r_game_users',$row);
    }
    
    public function getUserInfo($uid){
        $redis_key = REDIS_PREFIX.'Game_User'.$uid;
        $userInfo = $this->redis->hgetall($redis_key);
        if(!$userInfo){
            $userInfo = $this->db->getRowTable('r_game_users',[],"uid=$uid");
            if(!$userInfo){
                return [];
            }
            $userInfoJogger = $this->base->load('client')->getUserInfo($uid);
            $userInfo['nickname'] = isset($userInfoJogger['nickname']) ? $userInfoJogger['nickname'] : '';
            $userInfo['header'] = isset($userInfoJogger['header']) ? $userInfoJogger['header'] : '';
            //$userInfo['gift_count'] = $this->db->getOne("select count(*) from r_game_gift_record where uid='$uid'");
            
            //排名
            /*
            $redis_key1 = REDIS_PREFIX.'Game_Rank_User';
            $user_count = $this->redis->zcard($redis_key1);
            $user_rank = $this->redis->zrevrank($redis_key1,$uid);
            $userInfo['rank_per_cent'] = $user_rank === false ? '100' : $user_rank*100/$user_count;
            $userInfo['rank_per_cent'] .= '%';
            */
            
            $this->redis->hmset($redis_key,$userInfo);
            $this->redis->expire($redis_key,600);
        }
        return $userInfo;
    }
    
    public function updateUser($data){
        if(!$data['uid']){
            return false;
        }
        $uid = $data['uid'];
        $row = ['uid'=>$uid];
        isset($data['chapter']) && $row['chapter'] = $data['chapter'];
        $this->db->updateRowTable('r_game_users',$row);
        $this->redis->del(REDIS_PREFIX.'Game_User'.$uid);
    }
    
    public function checkNickname($nickname){
        $result = -1;

        $len = mb_strlen($nickname, 'utf-8');

        // 判断昵称长度与格式是与合法
        if ($len >= 1 && $len <= 20 && preg_match('/^[A-Za-z0-9\x80-\xff\s\']+$/', $nickname))
        {
            // 判断昵称是否存在违禁词
            if (!$this->base->load('badwords')->check($nickname))
            {
                // 判断昵称是否已被使用
                $checkSql = "select id from r_game_monsters where nickname='{$nickname}'";
                !empty($uid) && $checkSql .= " and uid != '{$uid}'";
                $checkSql .= ' limit 1';
                if (!$this->db->getOne($checkSql))
                {
                    $result = 1;
                } else
                {
                    $result = -3;
                }
            } else
            {
                $result = -2;
            }
        }

        return $result;
    }
    
    public function getMonsterInfo($id){
        $redis_key = REDIS_PREFIX.'Game_Monster_'.$id;
        $monster = $this->redis->hgetall($redis_key);
        if(!$monster){
            $monster = $this->db->getRowTable('r_game_monsters',[],"id=$id");
            if(!$monster){
                return [];
            }
            $starttime = time()-3600;
            $uid = $monster['uid'];
            $buff = $this->db->getOne("select count(distinct from_openid) from r_game_buff_record_wx where to_uid='$uid' and addtime>=$starttime");
            $monster['buff'] = $buff;
            $monster['level'] = $this->getLevelByExperience($monster['experience']);
            $this->redis->hmset($redis_key,$monster);
            $this->redis->expire($redis_key,1800);
        }
        return $monster;
    }
    
    public function addMonster($uid,$nickname){
        $hp = rand(3,24);
        $attack = rand(3,27-$hp);
        $defense = 30-$attack-$hp;
        $row = [
            'uid' => $uid,
            'nickname' => $nickname,
            'addtime' => time(),
            'hp' => $hp,
            'current_hp' => 0,
            'attack' => $attack,
            'defense' => $defense,
            'points' => $hp+$attack+$defense,
            'monster_type' => 1
        ];
        $id = $this->db->insertRowTable('r_game_monsters',$row);
        return $id;
    }
    
    public function updateMonster($data){
        if(!isset($data['id'])){
            return false;
        }
        $id = $data['id'];
        $row['id'] = $id;
        isset($data['nickname']) && $row['nickname'] = $data['nickname'];
        isset($data['hp']) && $row['hp'] = $data['hp'];
        isset($data['attack']) && $row['attack'] = $data['attack'];
        isset($data['defense']) && $row['defense'] = $data['defense'];
        isset($data['current_hp']) && $row['current_hp'] = $data['current_hp'];
        isset($data['experience']) && $row['experience'] = $data['experience'];
        isset($data['monster_type']) && $row['monster_type'] = $data['monster_type'];
        isset($data['points']) && $row['points'] = $data['points'];
        
        $this->db->updateRowTable('r_game_monsters',$row);
        $this->redis->del(REDIS_PREFIX.'Game_Monster_'.$id);
    }
    
    /*
     * 当没有poi时，boss_type 为 id
     */
    public function getBossInfo($boss_type,$poi=null,$uid=null){
        if($poi === null && !is_numeric($boss_type)){
            $id = $boss_type;
        }else{
            $id = md5($boss_type.'_'.$poi);
        }
        $redis_key = REDIS_PREFIX.'Game_Boss_'.$id;
        $boss = $this->redis->hgetall($redis_key);
        if(!$boss){
            if($poi === null){
                return [];
            }
            $boss_rule = $this->db->getRow("select name,img_icon,img_big,hp,attack,attack_reduce from r_game_boss_rules where boss_type='$boss_type' limit 1");
            $boss = [
                'id' => $id,
                'uniqid' =>uniqid($boss_type.$poi.'_'),
                'boss_type' => $boss_type,
                'poi' => $poi,
                'name' => $boss_rule['name'],
                'img_icon' => $boss_rule['img_icon'],
                'img_big' => $boss_rule['img_big'],
                'hp' => $boss_rule['hp'],
                'current_hp' => $boss_rule['hp'],
                'attack' => $boss_rule['attack'],
                'attack_reduce' => $boss_rule['attack_reduce'],
                'uid' => $uid,
                'team_members' => "[]",
                'gift_uids' => "[]"
            ];
            $this->redis->hmset($redis_key,$boss);
            $this->redis->expire($redis_key,1800);
        }
        $boss['team_members'] = json_decode($boss['team_members'],true);
        $boss['gift_uids'] = json_decode($boss['gift_uids'],true);
        if($boss['current_hp'] < 0){
            $boss['current_hp'] = 0;
        }
        return $boss;
    }
    
    public function careMonster($from_uid,$monster_id){
        $monsterInfo = $this->getMonsterInfo($monster_id);
        $to_uid = $monsterInfo['uid'];
        $current_hp = $monsterInfo['current_hp'] + 0.2*$monsterInfo['hp'];
        if($current_hp > $monsterInfo['hp']){
            $current_hp = $monsterInfo['hp'];
        }
        $row = [
            'id' => $monster_id,
            'current_hp' => $current_hp
        ];
        $this->updateMonster($row);
        
        //保存记录
        $row = [
            'from_uid'=>$from_uid,
            'to_uid'=>$to_uid,
            'monster_id'=>$monster_id,
            'addtime'=>time()
        ];
        $this->db->insertRowTable('r_game_care_record',$row);
        
        //更新用户
        $this->db->update("update r_game_users set cared_count=cared_count+1 where uid='{$to_uid}'");
        return $current_hp;
    }
    
    public function careMonsterWx($from_openid,$nickname,$header,$monster_id){
        $monsterInfo = $this->getMonsterInfo($monster_id);
        $to_uid = $monsterInfo['uid'];
        $current_hp = $monsterInfo['current_hp'] + 0.2*$monsterInfo['hp'];
        if($current_hp > $monsterInfo['hp']){
            $current_hp = $monsterInfo['hp'];
        }
        $row = [
            'id' => $monster_id,
            'current_hp' => $current_hp
        ];
        $this->updateMonster($row);
        
        //保存记录
        $row = [
            'from_openid'=>$from_openid,
            'nickname' => $nickname,
            'header' => $header,
            'to_uid'=>$to_uid,
            'monster_id'=>$monster_id,
            'addtime'=>time()
        ];
        $this->db->insertRowTable('r_game_care_record_wx',$row);
        
        //更新用户
        $this->db->update("update r_game_users set cared_count=cared_count+1 where uid='{$to_uid}'");
        return $current_hp;
    }
    
    public function giveBuff($from_openid,$nickname,$header,$to_uid){
        $row = [
            'from_openid' => $from_openid,
            'nickname' => $nickname,
            'header' => $header,
            'to_uid' => $to_uid,
            'addtime' => time()
        ];
        $this->db->insertRowTable('r_game_buff_record_wx',$row);
        
        //更新用户
        $this->db->update("update r_game_users set given_buff_count=given_buff_count+1 where uid='{$to_uid}'");
    }
    
    /*
     * 通过经验值获得等级
     */
    public function getLevelByExperience($experience){
        $levelArr = [
            5,
            7,
            10,
            14,
            19,
            27,
            38,
            53,
            74,
            103,
            145,
            202,
            283,
            397,
            556,
            778,
            1089,
            1525,
            2134,
            2988,
            4183,
            5857,
            8199,
            11479,
            16071,
            22499,
            31499,
            44099,
            61738,
            86434,
            INF
        ];
        foreach($levelArr as $k=>$v){
            if($v > $experience){
                return $k+1;
            }
        }
    }
    
    /*
     * 通过等级获得提供的经验值
     */
    public function getAddExperienceByLevel($level){
        $arr = [
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            14,
            16,
            18,
            20,
            23,
            26,
            29,
            33,
            38,
            42,
            48,
            54,
            61,
            69,
            78,
            88,
            100,
            113,
            127,
            144,
            163,
            184,
            208
        ];
        return array_key_exists($level-1,$arr) ? $arr[$level] : 0;
    }
    
    /*
     * 获得排行
     */
    public function getRankList($type,$id){
        $list = [];
        $rank = false;
        if($type==0){
            //个人，杀死数=>uid
            $redis_key = REDIS_PREFIX.'Game_Rank_User';
            $rows = $this->redis->zrevrange($redis_key,0,100,'withscores');
            foreach($rows as $uid=>$points){
                $list[] = [
                    'userInfo' => $this->getUserInfo($uid),
                    'points' => $points
                ];
            }
            $rank = $this->redis->zrevrank($redis_key,$id);
        }elseif($type == 1){
            //城市，杀死数=>$uid
            $redis_key = REDIS_PREFIX.'Game_Rank_City';
            $rows = $this->redis->zrevrange($redis_key,0,100,'withscores');
            $bests = $this->redis->hgetall(REDIS_PREFIX.'Game_City_Best');
            foreach($rows as $city=>$points){
                if($city==''){
                    continue;
                }
                $best = explode(',',$bests[$city]);
                $list[] = [
                    'city' => $city,
                    'points' => $points,
                    'userInfo' => $this->getUserInfo($best[0])
                ];
            }
        }elseif($type == 2){
            //最高属性，得分=>$monster_id
            $redis_key = REDIS_PREFIX.'Game_Rank_Monster';
            if(!$this->redis->exists($redis_key)){
                $_rows = $this->db->getAll("select points,id from r_game_monsters order by points desc limit 100");
                foreach($_rows as $row){
                    $this->redis->zadd($redis_key,$row['points'],$row['id']);
                }
                $this->redis->expire($redis_key,1800);
            }
            $rows = $this->redis->zrevrange($redis_key,0,100,'withscores');
            foreach($rows as $monster_id=>$points){
                $monsterInfo = $this->getMonsterInfo($monster_id);
                $list[] = [
                    'monsterInfo'=>$monsterInfo,
                    'userInfo'=>$this->getUserInfo($monsterInfo['uid']),
                    'points'=>$points
                ];
            }
            $rank = $this->redis->zrevrank($redis_key,$id);
        }elseif($type == 3){
            //探索最多，poi数=>uid
            $redis_key = REDIS_PREFIX.'Game_Rank_Explore';
            $rows = $this->redis->zrevrange($redis_key,0,100,'withscores');
            foreach($rows as $uid=>$points){
                $list[] = [
                    'userInfo' => $this->getUserInfo($uid),
                    'points' => $points
                ];
            }
            $rank = $this->redis->zrevrank($redis_key,$id);
        }
        return compact('list','rank');
    }
    
    /*
     * 刷新排行
     */
    public function updateRank($type,$data){
        if($type==0){
            //个人
            $redis_key = REDIS_PREFIX.'Game_Rank_User';
            $this->redis->zincrby($redis_key,1,$data['uid']);
        }elseif($type == 1){
            //城市
            $redis_key = REDIS_PREFIX.'Game_Rank_City';
            $this->redis->zincrby($redis_key,1,$data['city']);
            
            //城市第一名
            $redis_key1 = REDIS_PREFIX.'Game_City_Best';
            $best = $this->redis->hget($redis_key1,$data['city']);
            if($best){
                $best = explode(',',$best);
                if($data['win_count'] > $best[1]){
                    $best = implode(',',[$data['uid'],$data['win_count']]);
                    $this->redis->hset($redis_key1,$data['city'],$best);
                }
            }else{
                $best = implode(',',[$data['uid'],$data['win_count']]);
                $this->redis->hset($redis_key1,$data['city'],$best);
            }
            $this->redis->expire($redis_key1,2592000);
        }elseif($type == 3){
            //探索最多
            $redis_key = REDIS_PREFIX.'Game_Rank_Explore';
            $this->redis->zincrby($redis_key,1,$data['uid']);
        }
        //一个月过期
        $this->redis->expire($redis_key,2592000);
    }
    
    public function getCareList($uid,$start=0,$length=50){
        $res = $this->db->getAll("select from_openid,count(*) as care_count,nickname,header from r_game_care_record_wx where to_uid='$uid' group by from_openid order by care_count desc limit {$start},{$length}");
        $result = [];
        foreach($res as $row){
            $result[] = [
                'care_count' => $row['care_count'],
                'from_user' => $row
            ];
        }
        return $result;
    }
    
    public function getBuffList($uid,$start=0,$length=50){
        $res = $this->db->getAll("select from_openid,count(*) as buff_count,nickname,header from r_game_buff_record_wx where to_uid='$uid' group by from_openid order by buff_count desc limit {$start},{$length}");
        $result=[];
        foreach($res as $row){
            $result[] = [
                'buff_count' => $row['buff_count'],
                'from_user' => $row
            ];
        }
        return $result;
    }
    
    /*
     * 添加战斗记录
     */
    public function addFightResult($data){
        $uid = $data['uid'];
        $result = $data['result'];
        $poi = $data['poi'];
        
        $explored = $this->db->getOne("select id from r_game_fight_record where uid='$uid' and poi='$poi' limit 1");
        
        //保存结果
        $row = ['uid'=>$uid];
        isset($data['poi']) && $row['poi'] = $data['poi'];
        isset($data['boss_type']) && $row['boss_type'] = $data['boss_type'];
        $row['result'] = $result;
        isset($data['city']) && $row['city'] = $data['city'];
        isset($data['address']) && $row['address'] = $data['address'];
        isset($data['boss_id']) && $row['boss_id'] = $data['boss_id'];
        $row['addtime'] = time();
        $this->db->insertRowTable('r_game_fight_record',$row);
        
        //更新用户数据
        $sql = 'update r_game_users set fight_count=fight_count+1';
        if($result==1){
            $sql .= ' , win_count=win_count+1';
        }
        if($data['boss_type']!=0){
            $sql .= ' , boss_fight_count=boss_fight_count+1';
            if($result==1){
                $sql .= ' ,boss_win_count=boss_win_count+1';
            }
        }
        $sql .= " where uid='$uid'";
        $this->db->update($sql);
        $redis_key = REDIS_PREFIX.'Game_User'.$uid;
        $this->redis->del($redis_key);
        
        //更新排行
        if($result){
            $userInfo = $this->getUserInfo($uid);
            //个人
            $this->updateRank(0,$userInfo);
            //城市
            $this->updateRank(1,$userInfo);
        }
        if(!$explored){
            //更新用户
            $this->db->update("update r_game_users set poi_count=poi_count+1 where uid={$uid}");
            
            //探索
            $this->updateRank(3,$row);
        }
    }
    
    /*
     * 更新战斗记录
     */
    public function updateFightResult($data){
        if(!isset($data['id'])){
            return false;
        }
        $result = 0;
        $uid = $data['uid'];
        $result = $data['result'];
        $row = ['id'=>$data['id']];
        isset($data['poi']) && $row['poi'] = $data['poi'];
        isset($data['boss_type']) && $row['boss_type'] = $data['boss_type'];
        if(isset($data['result'])){
            $result = $data['result'];
            $row['result'] = $result;
        }
        isset($data['city']) && $row['city'] = $data['city'];
        isset($data['address']) && $row['address'] = $data['address'];
        isset($data['boss_id']) && $row['boss_id'] = $data['boss_id'];
        
        $this->db->updateRowTable('r_game_fight_record',$row);
        
        if($result){
            //更新用户数据
            $sql = "update r_game_users set win_count=win_count+1";
            if(isset($data['boss_type']) && $data['boss_type']!=0){
                $sql .= ' ,boss_win_count=boss_win_count+1';
            }
            $sql .= " where uid='$uid'";
            $this->db->update($sql);
            $redis_key = REDIS_PREFIX.'Game_User'.$uid;
            $this->redis->del($redis_key);
            $userInfo = $this->getUserInfo($uid);
            
            //更新排行
            //个人
            $this->updateRank(0,$userInfo);
            //城市
            $this->updateRank(1,$userInfo);
        }
    }
    
    /*
     * 跑步后更新属性
     */
    public function updateMonsterByRunData($uid,$runData){
        if(!$this->gameIsOn()){
            return;
        }
        //更新用户
        $this->db->update("update r_game_users set run_times=run_times+1, run_mileage=run_mileage+{$runData['mileage']} where uid={$uid}");
        
        //更新宝宝
        $monsterInfo = $this->db->getRow("select * from r_game_monsters where uid='$uid' limit 1");
        if(!$monsterInfo || !$monsterInfo['current_hp']){
            return;
        }
        $monster_id = $monsterInfo['id'];
        //$monsterInfo = $this->getMonsterInfo($monster_id);
        $row = [
            'id' => $monster_id,
            'hp' => $monsterInfo['hp'] + floor($runData['mileage']),
            'defense' => $monsterInfo['defense']+1,
        ];
        //配速 min/km
        $pace = 60/$runData['speed'];
        if($pace < 5){
            $row['attack'] = $monsterInfo['attack']+2;
        }elseif($pace < 10){
            $row['attack'] = $monsterInfo['attack']+1;
        }
        $row['points'] = $row['hp'] + $row['defense'];
        $row['points'] += isset($row['attack']) ? $row['attack'] : $monsterInfo['attack'];
        
        $this->updateMonster($row);
    }
    
    /*
     * 更新boss
     */
    public function updateBoss($data){
        if(!isset($data['id'])){
            return false;
        }
        $id = $data['id'];
        $redis_key = REDIS_PREFIX.'Game_Boss_'.$id;
        $row = [];
        isset($data['team_members']) && $row['team_members'] = json_encode($data['team_members']);
        isset($data['gift_uids']) && $row['gift_uids'] = json_encode($data['gift_uids']);
        $this->redis->hmset($redis_key,$row);
        
        if(isset($data['monster_attack']) && $data['monster_attack'] > 0){
            $this->redis->hincrby($redis_key,'current_hp',-$data['monster_attack']);
        }
        
        $this->redis->expire($redis_key,1800);
    }
    
    /*
     * 游戏是否启用
     */
    public function gameIsOn(){
        $isOpen = false;
        $gameInit = $this->redis->get(REDIS_PREFIX . 'gameIsOpen');
        if($gameInit){
            $gameInit = json_decode($gameInit, true);
            $starttime = strtotime($gameInit['start_time']);
            $endtime = strtotime($gameInit['end_time']);
            if($gameInit['is_show'] == 1 && $starttime < time() && $endtime > time()){
                $isOpen = true;
            }
        }
        return $isOpen;
    }
    
    /*
     * 获取宝箱
     * param  channel  应用渠道(0:app内;1:网页)
     */
    public function getGift($uid,$poi,$channel = 0){
        if(!empty($poi)){
            $isDraw = $this->redis->get(REDIS_PREFIX . "onlyPoiDrawOnce" . $poi);
            if($isDraw){
                return (object)[];
            }
            $this->redis->set(REDIS_PREFIX . "onlyPoiDrawOnce" . $poi, 1);
            $this->redis->expire(REDIS_PREFIX . "onlyPoiDrawOnce" . $poi, 300);
        }
        
        //读取参与抽奖的奖品
        $prizeList = $this->db->getAll("select * from r_game_gifts where is_show = 0 and channel = {$channel}");
        $drawInfo = array();
        $winningInfo = array();
        $date = date('Ymd');
        if($prizeList){
            foreach ($prizeList as &$v) {
                $drawInfo[$v['gid']] = $v['name'];
                $drawInfo[$v['name']] = $v['img'];
                $drawInfo['giftType'.$v['gid']] = $v['gift_type']; //存奖品类型
                if($v['isInfinite'] == 0){  //考虑奖品个数
                    if($v['remain'] == 0){   //剩余数量为0，概率置0
                        $v['chance'] = 0;
                    }
                }

                for($i=0; $i<$v['chance']; $i++){
                    $result[] = $v['gid'];
                }
            }

            shuffle($result);
            $prizeId = $result[array_rand($result)]; //所获奖品
            //暂存用户中奖信息
            $this->redis->set(REDIS_PREFIX . "gameDrawUid_" . $uid, $prizeId);

            //更新奖品库存
            $this->db->update("update r_game_gifts set remain = remain - 1 where isInfinite = 0 and is_show = 0 and gid = {$prizeId}");

            //虚拟物品加入个人账户
            if($drawInfo['giftType'.$prizeId] == 2 && $channel == 0){
                if(strstr($drawInfo[$prizeId], '*')){
                    $giftArr = explode('*', $drawInfo[$prizeId]);
                    $giftName = $giftArr[0];
                    $giftCount = $giftArr[1];
                    if(strstr($giftName, '经验值')){
                        /*$this->db->update("update r_game_monsters set experience = experience + {$giftCount} where uid = {$uid}");*/
                        $monster = $this->db->getRow("select * from r_game_monsters where uid = {$uid} limit 1");
                        if($monster){
                            $newMonster = $this->getLevelUpMonster($monster, $giftCount);
                            $this->updateMonster($newMonster);
                        }
                    }
                    if(strstr($giftName, '正能量')){
                        //正能量表更新
                        $this->base->load('client')->userEnergyChange($uid,'gameGift',[
                            'energy_add' => $giftCount
                        ]);
                    }
                }
            }

            if($channel == 0){
                //更新个人获取的礼物数
                $this->db->update("update r_game_users set gift_count = gift_count + 1 where uid = {$uid}");
            }

            //组装中奖信息
            $winningInfo = array(
                'id' => $prizeId,
                'name' => $drawInfo[$prizeId],
                'img' => $drawInfo[$drawInfo[$prizeId]],
                'giftType' => $drawInfo['giftType'.$prizeId]
            );
            
            if($drawInfo['giftType'.$prizeId] == 2 && $channel == 1){
                if(strstr($drawInfo[$prizeId], '贺卡')){
                    $cardArr = [
                        '新的1年开始，祝好事接2连3，心情4季如春，生活5颜6色，7彩缤纷，偶尔8点小财，烦恼抛到9霄云外!请接受我10心10意的祝福。',
                        '送你一件外套，前面是平安，后面是幸福，吉祥是领子，如意是袖子，快乐是扣子，口袋里满是温暖，穿上吧，让它相伴你的每一天!',
                        '天增岁月人增寿，春满乾坤福满门。三羊开泰送吉祥，五福临门财源茂。恭祝新春快乐，幸福安康！！',
                        '祝你一帆风顺，二龙腾飞，三羊开泰，四季平安，五福临门，六六大顺，七星高照，八方来财，九九同心，十全十美，百事亨通，千事吉祥，万事如意!',
                        '酒越久越醇，水越流越清，世间沧桑越流越淡，朋友情谊越久越真。衷心祝福吾友度过一个祥和美满的新春!',
                        '对你的思念像袅袅的轻烟不绝如缕，对你的祝福是潺潺的小溪叮咚作响。或许岁月将往事褪色，或许空间将彼此隔离。但值得珍惜的依然是你给我的情谊。再次对你说声：新春快乐!',
                        '值此新春之际，祝您：大财、小财、意外财，财源滚滚;亲情、友情、爱情，情情如意;官运、福运、桃花运，天天走运;爱人、亲人、友人，人人平安!',
                        '拜年啦!咱都老相识了，客套话就不说了，给你送句实实在在的祝福：兜里有钱，办事有人，生活有乐，事业有成，朋友有情，人生有福!',
                        '我的祝福是个宝，幸运人儿能收到，鸡年事业直登高，金银财宝装满包，家人平安开心笑，身体健康金钟罩，天天好运来围绕!',
                        '愿你有高跟鞋也有跑鞋，喝茶也喝酒。愿你有勇敢的朋友，有牛逼的对手。愿你对过往的一切情深意重，但从不回头。愿你特别美丽，特别平静，特别凶狠，也特别温柔。'
                    ];
                    $i = mt_rand(1, 10);
                    $winningInfo['name'] = $cardArr[$i];
                }
            }
            $recordId = 0;
            if($winningInfo['name'] != '空'){
                //生成奖品记录
                $params = array('gift_id' => $prizeId, 'channel' => $channel, 'addtime' => time());
                if($channel == 0){
                    $params['uid'] = $uid;
                }else{
                    $params['open_id'] = $uid;
                }
                $recordId = $this->db->insertRowTable('r_game_gift_record', $params);
            }
            $winningInfo['rid'] = $recordId;
            return $winningInfo;
        }else{
            return (object)[];
        }
    }

    /*
     * 我的奖品列表
     */
    public function getGiftList($uid){
        $sql = "SELECT r.id,r.gift_id,r.is_delivery,g.name,g.img FROM r_game_gift_record r LEFT JOIN r_game_gifts g ON r.gift_id = g.gid WHERE g.is_show = 0 and g.gift_type = 1 and r.uid = {$uid}";
        $giftList = $this->db->getAll($sql);
        return $giftList;
    }

    /*
     * 填写地址
     */
    public function recordAdress($params){
        $success = $this->db->updateRowTable('r_game_gift_record',$params);
        return $success;
    }
    
    /*
     * 获得升级后的属性
     */
    public function getLevelUpMonster($monster,$experience_add){
        $new_experience = $monster['experience'] + $experience_add;
        $level_up = $this->getLevelByExperience($new_experience) - $this->getLevelByExperience($monster['experience']);
        $monster['experience'] = $new_experience;
        if($level_up){
            $hp_up = 0;
            for($i=0;$i<$level_up;$i++){
                $hp_up += rand(1,15);
            }
            $monster['hp'] = $monster['hp'] + $hp_up;
            $attack_up = 0;
            for($i=0;$i<$level_up;$i++){
                $attack_up +=rand(1,10);
            }
            $monster['attack'] = $monster['attack'] + $attack_up;
            $defense_up = 0;
            for($i=0;$i<$level_up;$i++){
                $defense_up +=rand(1,10);
            }
            $monster['defense'] = $monster['defense'] + $defense_up;
            $monster['points'] = $monster['hp'] + $monster['attack'] + $monster['defense'];
        }
        return $monster;
    }
    
    /**
     * 获取用户的微信公众号OpenID
     */
    public function getWxPubOpenId()
    { 
        return !empty($_COOKIE['wxpo']) ? $_COOKIE['wxpo'] : NULL;
    }
    
    /**
    * 微信授权
    */
    public function checkWxPubOpenId()
    {
        if(!$this->getWxPubOpenId())
        {
            $state = md5($this->_appId . $this->_appSecret . time());
            $param = array(
                'appid' => $this->_appId,
                'redirect_uri' => $this->_redirectUrl,
                'response_type' => 'code',
                'scope' => 'snsapi_userinfo',
                'state' => $state
            );
            $param = http_build_query($param);
            $wxUrl = $this->_uri ."authorize?" . $param . "#wechat_redirect";

            $rurl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            setcookie('rurl', $rurl, time() + 864000, '/', '.hupu.com', FALSE, TRUE);
            setcookie('rurl', $rurl, time() + 864000, '/', '.ijoggers.com', FALSE, TRUE);

            common::go($wxUrl);
        }
    }
}
